from server.storage import Storage
from server.metadata import Metadata

import matplotlib.pyplot as plt
from io import BytesIO

import requests
from requests_toolbelt import MultipartEncoder

def init():
    Storage.init()
    Metadata.init()
    inodeNames = Storage.listInodeName()
    for inodeName in inodeNames:
        inodeInfo = Storage.queryInode(inodeName)
        Metadata.addInode(inodeName, inodeInfo)

def test():
    inodeNames = Storage.listInodeName()
    for inodeName in inodeNames[:1]:
        inode = Metadata.getInode(inodeName)
        bucketName = str(inode[0], encoding="utf-8")
        filepath = str(inode[1], encoding="utf-8")
        binary = Storage.queryFile(bucketName, filepath)

        img = plt.imread(BytesIO(binary))
        plt.imshow(img)
        plt.show()

def testUpload():
    appid = '01234567890123456789012345678901'
    bucket = 'webspider'
    secretKey = '98765432109876543210987654321098'
    fileName = '0042_ribera.jpg'
    url = 'http://127.0.0.1:5000/files?appid=' + appid + '&bucket=' + bucket + '&secretKey=' + secretKey + '&fileName=' + fileName

    fd = open('D:/zz/git/webspider/osd/server/storage/bucket_data/default/upload/content_images/artist/0042_ribera.jpg', 'rb')

    # binary上传文件
    '''
    files = {'file': fd}
    response = requests.post(url = url, files = files, headers = {'Content-Type':'binary'})
    print(response)
    '''

    # from_data上传文件
    data = MultipartEncoder(fields = {'file': (fileName, fd, 'text/xml')})
    response = requests.post(url = url, data = data, headers = {'Content-Type': data.content_type})

    status_code = response.status_code # HTTP请求的返回状态，200表示连接成功，404表示失败 
    text = response.text # HTTP响应内容的字符串形式，即url对应的页面内容 
    encoding = response.encoding # 从HTTP header中猜测的响应内容编码方式( 
    apparent_encoding = response.apparent_encoding # 从内容中分析出的响应内容编码方式（备选编码方式） 
    content = response.content # HTTP响应内容的二进制形式

    if status_code == 200:
        print(text)
    else:
        print(status_code)

if __name__ == '__main__':
    init()
    # test()
    # testUpload()
